package cn.gotom.core.web;

import org.apache.log4j.Logger;
import org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter;

import cn.gotom.coding.CodingModule;
import cn.gotom.core.dao.UniversalDao;
import cn.gotom.core.dao.jpa.UniversalDaoJpa;
import cn.gotom.core.example.Service;
import cn.gotom.core.example.ServiceImpl;
import cn.gotom.util.GuiceUtils;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.google.inject.persist.jpa.JpaPersistModule;
import com.google.inject.servlet.GuiceServletContextListener;
import com.google.inject.servlet.ServletModule;
import com.google.inject.struts2.Struts2GuicePluginModule;

/**
 * 
 * 
 * @author peixere@qq.com
 */
public class GuiceListener extends GuiceServletContextListener
{
	private final Logger log = Logger.getLogger(getClass());
	protected Injector injector;

	protected void createInjector()
	{
		ServletModule servletModule = new ServletModule()
		{
			@Override
			protected void configureServlets()
			{
				bind(GuicePersistFilter.class).in(Singleton.class);
				filter("/*").through(GuicePersistFilter.class);
				bind(Service.class).to(ServiceImpl.class);
				bind(UniversalDao.class).to(UniversalDaoJpa.class);
				log.debug("servletPersistModule");
				bind(StrutsPrepareAndExecuteFilter.class).in(Singleton.class);
				filter("/*").through(StrutsPrepareAndExecuteFilter.class);
				log.debug("servletStrutsModule");				
			}
		};
		injector = Guice.createInjector(new Struts2GuicePluginModule(),/* new CodingModule(),*/ new JpaPersistModule("ApplicationEntityManager"), servletModule);
		GuiceUtils.getInstance().setInjector(injector);
		log.debug("createInjector：" + injector);
	}

	@Override
	public Injector getInjector()
	{
		if (injector == null)
			createInjector();
		return injector;
	}

}
